from bpy.types import Context
from ....addon.naming import FluidLabNaming
from ....libs.functions.get_common_vars import get_common_vars
from ....libs.functions.geometry_nodes import set_exposed_attributes_of_gn as set_prop


def props_update_mesh_settings(self, context:Context, call_from:str) -> None:

    """ Update GN Mesh Settings Properties """
    fluid_mesh, ui = get_common_vars(context, get_fluid_mesh=True, get_ui=True)

    active_mesh = fluid_mesh.active
    ob = active_mesh.ob                
    GN_mod = ob.modifiers.get(FluidLabNaming.GN_MESH_MOD)

    if GN_mod and ui.main_modules == 'MESH':
        group_input = GN_mod.node_group.nodes.get("Group Input")
        if group_input:

            if call_from == "min_max_value":
                set_prop(GN_mod, "Min", getattr(self, call_from), False)
                set_prop(GN_mod, "Max", getattr(self, call_from), False)

            elif call_from == "collection_grains":
                set_prop(GN_mod, "Collection Grains", getattr(self, call_from), False)
            
            elif call_from == "p_or_g":

                # Points or Geometry GN:
                value = True if getattr(self, call_from) == '1' else False
                set_prop(GN_mod, "Points/Geometry", value, False)

                # Points or Geometry Meterial:
                # mat = next((mat.material for mat in ob.material_slots if mat.name.endswith(FluidLabNaming.MAT_BASIC_GRAIN)), None)
                mat = next((mat.material for mat in ob.material_slots if mat.name.endswith("_Grain")), None)
                if mat:
                    mix_node = mat.node_tree.nodes.get("Points/Geometry")
                    if mix_node:
                        node_input = next((input for input in mix_node.inputs if input.enabled and input.identifier == "Factor_Float"), None)
                        if node_input:
                            setattr(node_input, "default_value", value)

            # Refresh GN:
            ob.update_tag()